package org.manon.json.util;

import java.lang.reflect.Method;
import java.lang.StringBuilder;
import java.util.ArrayList;
import java.util.List;

import org.manon.json.JSONException;
import org.manon.json.annotation.JSon;

/**
 * Utility methods for class.
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class ClassUtils {

	/**
	 * Private Constructor.
	 */
	private ClassUtils() {
	}
	
	
	/**
	 * generate a Getter method for the property
	 */
	public static String getGetter(String property) {
		return formatMethod("get", property);
	}
	
	/**
	 * generate a Setter method for the property
	 */
	public static String getSetter(String property) {
		return formatMethod("set", property);
	}
	
	public static String formatMethod(String prefix,String property) {
		
		if (property == null) {
			throw new IllegalArgumentException("The property must be not null");
		}
		
		final StringBuilder builder = new StringBuilder();
		builder.append(prefix);
		builder.append(Character.toUpperCase(property.charAt(0)));
		builder.append(property.substring(1));
		return builder.toString();
		
	}
	
	public static Method getGetter(Class<?> clazz, String propertyName) {
		try {
			return  clazz.getMethod(ClassUtils.getGetter(propertyName));
		} catch (Exception cause) {
			throw new IllegalStateException("No Getter for property ["+ propertyName + "] in class [" + clazz.getName() +"]" , cause);
		} 
	}
	
	
	public static String firstLetterToUpperCase(String string) {

		final StringBuilder builder = new StringBuilder();
		builder.append(Character.toUpperCase(string.charAt(0)));
		if (string.length() > 1) {
			builder.append(string.substring(1));
		}
		return builder.toString();
	}
	
	public static String[] path(Class<?> entityClass) {
		final List<String> paths = new ArrayList<String>();
		path(paths,entityClass);
		return paths.toArray(new String[paths.size()]);
	}
	
	private static void path(List<String> paths,Class<?> clazz) {
		if (Object.class.equals(clazz)) {
			return;
		}
		JSon json = clazz.getAnnotation(JSon.class);
		
		if (json == null) {
			throw new JSONException("The class [" + clazz + "] hasn't @JSON annotation ?!?");
		}
		
		paths.add(0, (json.value().length() > 0) ? json.value() : clazz.getSimpleName());
		path(paths,clazz.getSuperclass());
	}
	
}